package com.marktrace.service.impl;

import com.alibaba.fastjson.JSON;
import com.marktrace.dao.DLocationMapper;
import com.marktrace.dao.TEquipmentMapper;
import com.marktrace.dao.TStudentMapper;
import com.marktrace.entity.DLocation;
import com.marktrace.entity.TEquipment;
import com.marktrace.service.LocationService;
import com.marktrace.util.AESUtil;
import com.marktrace.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LocationServiceImpl implements LocationService {

    @Autowired
    private DLocationMapper dLocationMapper;
    @Autowired
    private TStudentMapper tStudentMapper;
    @Resource(name="restTemplateForHttps")
    RestTemplate restTemplateForHttps;
    @Autowired
    private TEquipmentMapper tEquipmentMapper;
    @Value("${rpc.value}")
    private String rpcUrl;


    @Override
    public int deleteByPrimaryKey(Integer id) {
        return dLocationMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(DLocation record) {
        return dLocationMapper.insert(record);
    }

    @Override
    public DLocation selectByPrimaryKey(Integer id) {
        return dLocationMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<DLocation> selectAll() {
        return dLocationMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(DLocation record) {
        return dLocationMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Map<String, Object>> selectAllMap(Map<String, Object> map) {
        return dLocationMapper.selectAllMap(map);
    }

    @Override
    public List<Map<String, Object>> selectDetail(Map<String, Object> map) {
        return dLocationMapper.selectDetail(map);
    }

    @Override
    public int insertBatch(List<DLocation> list) {
        int i = 0;
        if(list.size()>0){
            i = dLocationMapper.insertBatch(list);
            pushDateRPC(i,list);
        }
        return i;
    }

    @Override
    public List<Map<String, Object>> rpcQueryInfo(Map<String, Object> map) {
        return dLocationMapper.rpcQueryInfo(map);
    }


    /**
     * 新开线程,调用远程接口推送
     * @param i
     * @param list
     */
    private void pushDateRPC(int i,List<DLocation> list){
        if(i>0){
            new Thread(() -> {
                List<Map<String, Object>> resultList = new ArrayList<>();
                List<DLocation> entityList;
                Map<String,List<DLocation>> groupMap = list.stream().collect(Collectors.groupingBy(DLocation::getEqno));
                Set<String> eqnoKeys = groupMap.keySet();
                for(String key:eqnoKeys){
                    entityList = groupMap.get(key);
                    String plateColor = "黄";
                    String dateTime = DateUtils.formatDateTime(entityList.get(0).getUploadtime());

                    TEquipment tEquipment = tEquipmentMapper.selectByEqno(key);

                    Map<String, Object> allParamMap = new HashMap<>();
                    allParamMap.put("licensePlat",tEquipment.getAddress());
                    allParamMap.put("plateColor",plateColor);
                    allParamMap.put("dateTime",dateTime);
                    List<Map<String, Object>> studentList = new ArrayList<>();
                    for(DLocation d:entityList){
                        String lno = d.getLno();
                        Map<String,Object> studentMap = tStudentMapper.selectByLno(lno);
                        studentList.add(studentMap);
                    }
                    allParamMap.put("data",studentList);
                    resultList.add(allParamMap);
                }
                String str = JSON.toJSONString(resultList);
                String pushParam = AESUtil.outBase64(str);
                String resultString = httpsClientForPostBody(rpcUrl,pushParam);
                String rpcResult = AESUtil.inBase64(resultString);
                Map<String,Object> paramMap = JSON.parseObject(rpcResult);
                String status = paramMap.get("status").toString();
                String msg = paramMap.get("msg").toString();
                log.info("远程调用结果:"+msg+"("+status+")");
            }).start();
        }
    }

    public String httpsClientForPostBody(String url,String bodyParam){

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.TEXT_PLAIN);

        HttpEntity<String> httpEntity = new HttpEntity<>(bodyParam, httpHeaders);

        ResponseEntity<String> responseEntity = restTemplateForHttps.postForEntity(url, httpEntity, String.class);
        String resultString = responseEntity.getBody();
        return resultString;
    }
}
